<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库" prop="fkStockUuid">
        <el-input
          v-model="queryParams.fkStockUuid"
          placeholder="请输入仓库"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓位" prop="fkStockPosUuid">
        <el-input
          v-model="queryParams.fkStockPosUuid"
          placeholder="请输入仓位"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="dialog_show_stockOut"
          v-hasPermi="['wms:stockOut:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:stockOut:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:stockOut:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wms:stockOut:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stockOutList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据编号" align="center" prop="docNum" width="200"/>
      <el-table-column label="单据日期" align="center" prop="docDt" width="150"/>
      <el-table-column label="仓库" align="center" prop="stockName" width="120" />
      <el-table-column label="仓位" align="center" prop="stockPosName" width="120"/>
      <el-table-column label="物料名称" align="center" prop="itemName" width="120"/>
      <el-table-column label="物料编码" align="center" prop="itemNum" width="180"/>
      <el-table-column label="物料规格" align="center" prop="itemSpecification" width="120"/>
      <el-table-column label="计量单位" align="center" prop="wmsDictMeasuringUnitDetail" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_dict_measuring_unit" :value="scope.row.wmsDictMeasuringUnitDetail"/>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="detailStockOutQty" width="120"/>
      <el-table-column label="出库员" align="center" prop="nickName" width="150"/>
      <el-table-column label="备注" align="center" prop="docNote" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="dialog_show_update(scope.row)"
            v-hasPermi="['wms:stockOut:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:stockOut:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-success"
            @click="showDialog_confirm(scope.row)"
            v-hasPermi="['oa:confirm:edit']"
            :disabled="scope.row.oaDictConfirmStatus !='waiting'"> 审核
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <stock-out ref="component_cmpStockOut" @ok="stockOut_done"/>
    <confirm ref="component_confirm" @ok="confirm_done"/>

  </div>
</template>

<script>
  import { listStockOut, getStockOut, delStockOut, addStockOut, updateStockOut,updInventory } from "@/api/wms/stockOut";
  import stockOut from "../stockOut/cmpStockOut";
  import confirm from "../../oa/confirm";
  import { listInventory } from "@/api/wms/inventory";

  export default {
    name: "StockOut",
    dicts: ['oa_dict_confirm_status','wms_dict_measuring_unit'],
    components: {stockOut,confirm},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 子表选中数据
        checkedWmsStockOut: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 出库单管理表格数据
        stockOutList: [],
        // 出库单管理表格数据
        wmsStockOutList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          wmsDictStockOutType: null,
          fkStockUuid: null,
          fkStockPosUuid: null,
          docNum: null,
          docTitle: null,
          docDt: null,
          fkAttentionUserId: null,
          fkConfirmUserId: null,
          docNote: null,
          confirmDt: null,
          oaDictConfirmStatus: null,
          confirmNote: null,
          fkUserId: null,
          fkDeptId: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          oaDictConfirmStatus: [
            { required: true, message: "审核状态不能为空", trigger: "blur" }
          ],
          createBy: [
            { required: true, message: "创建者不能为空", trigger: "blur" }
          ],
          createTime: [
            { required: true, message: "创建时间不能为空", trigger: "blur" }
          ],
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 打开对话框：审核 */
      showDialog_confirm(row) {
        const stockOutUuid = row.stockOutUuid
        getStockOut(stockOutUuid).then(response => {
          console.log(response)
          response.data.wmsStockOutDetailsList.forEach(item=>{
            this.queryParams.fkStockUuid = row.fkStockUuid
            this.queryParams.fkStockPosUuid = item.fkStockPosUuid
            this.queryParams.fkItemUuid = item.fkItemUuid
            listInventory(this.queryParams).then(response => {
              this.inventoryList = response.rows;
              if(this.inventoryList.length>0){
                this.inventoryList.forEach(d=>{
                  if(item.differentQty>d.inventoryQty){
                    this.$alert('物料名称为'+d.itemName+',仓库名称为'+d.stockName+',仓位名称为'+d.stockPosName+'的记录将会产生负库存', '提示', {
                      confirmButtonText: '确定',
                    });
                  }
                })
              }else{
                this.$alert('所在仓库的仓位中的物料不存在即时库存将会产生负库存', '提示', {
                  confirmButtonText: '确定',
                });
              }
            });
          })
        });
        this.confirmPassed=row
        let obj = {
          tableName: 'wms_stock_out',
          uuidColumn: 'stock_out_uuid',
          fkUuid: row.stockOutUuid,
          attentionUserNickName: row.nickName,
          msg: `请审核生产领料管理申请, 单据编号：${row.docNum}`
        }
        this.$refs.component_confirm.showDialog_confirm(obj);

      },
      /** 查询出库单管理列表 */
      getList() {
        this.loading = true;
        this.queryParams.wmsDictStockOutType = '6'
        listStockOut(this.queryParams).then(response => {
          this.stockOutList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          stockOutUuid: null,
          wmsDictStockOutType: null,
          fkStockUuid: null,
          fkStockPosUuid: null,
          docNum: null,
          docTitle: null,
          docDt: null,
          fkAttentionUserId: null,
          fkConfirmUserId: null,
          docNote: null,
          confirmDt: null,
          oaDictConfirmStatus: "0",
          confirmNote: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          fkUserId: null,
          fkDeptId: null
        };
        this.wmsStockOutList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.stockOutUuid)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加出库单管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const stockOutUuid = row.stockOutUuid || this.ids
        getStockOut(stockOutUuid).then(response => {
          this.form = response.data;
          this.wmsStockOutList = response.data.wmsStockOutList;
          this.open = true;
          this.title = "修改出库单管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.wmsStockOutList = this.wmsStockOutList;
            if (this.form.stockOutUuid != null) {
              updateStockOut(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addStockOut(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const stockOutUuids = row.stockOutUuid || this.ids;
        this.$modal.confirm('是否确认删除出库单管理编号为"' + stockOutUuids + '"的数据项？').then(function() {
          return delStockOut(stockOutUuids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 出库单管理序号 */
      rowWmsStockOutIndex({ row, rowIndex }) {
        row.index = rowIndex + 1;
      },
      /** 出库单管理添加按钮操作 */
      handleAddWmsStockOut() {
        let obj = {};
        obj.wmsDictStockOutType = "";
        obj.fkStockUuid = "";
        obj.fkStockPosUuid = "";
        obj.docNum = "";
        obj.docTitle = "";
        obj.docDt = "";
        obj.fkAttentionUserId = "";
        obj.fkConfirmUserId = "";
        obj.docNote = "";
        obj.confirmDt = "";
        obj.oaDictConfirmStatus = "";
        obj.confirmNote = "";
        obj.fkUserId = "";
        obj.fkDeptId = "";
        this.wmsStockOutList.push(obj);
      },
      /** 出库单管理删除按钮操作 */
      handleDeleteWmsStockOut() {
        if (this.checkedWmsStockOut.length == 0) {
          this.$modal.msgError("请先选择要删除的出库单管理数据");
        } else {
          const wmsStockOutList = this.wmsStockOutList;
          const checkedWmsStockOut = this.checkedWmsStockOut;
          this.wmsStockOutList = wmsStockOutList.filter(function(item) {
            return checkedWmsStockOut.indexOf(item.index) == -1
          });
        }
      },
      /** 复选框选中数据 */
      handleWmsStockOutSelectionChange(selection) {
        this.checkedWmsStockOut = selection.map(item => item.index)
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('wms/stockOut/export', {
          ...this.queryParams
        }, `wms_stockOut.xlsx`)
      },
      /** 对话框：显示 = 采购申请 */
      dialog_show_stockOut() {
        this.$refs.component_cmpStockOut.wmsDictStockOutType = '6'
        this.$refs.component_cmpStockOut.dialog_show_stockOut();
      },
      /** 选择订单明细完成 */
      stockOut_done() {
        this.getList()
      },

      /** 对话框：显示 = 采购申请 */
      dialog_show_update(row) {
        console.log(row)
        this.$refs.component_cmpStockOut.stockOutUuid = row.stockOutUuid||this.ids
        this.$refs.component_cmpStockOut.oaDictConfirmStatus = row.oaDictConfirmStatus
        this.$refs.component_cmpStockOut.wmsDictStockOutType = '6'
        this.$refs.component_cmpStockOut.dialog_show_update();
      },
      confirm_done() {
        this.getList()
        this.updInventory()
      },

      /* 更新库存 */
      updInventory(){
        const h = this.$createElement;

        this.$notify({
          title: '领料单据编号：' + this.confirmPassed.docNum,
          message: h('i', { style: 'color: teal'}, '领料出库单审批通过，库存将被更新！')
        });
        updInventory(this.confirmPassed.stockOutUuid).then(response => {
          console.log(response)
        });
      },
    }
  };
</script>
